//app.js
var util = require('./utils/utils.js');
var api = require('./api.js');
App({
    is_on_launch: true,
    onLaunch: function () {
        console.log(wx.getSystemInfoSync());
        // this.getStoreData();
        this.getCatList();
        var access_token = wx.getStorageSync("access_token");
        console.log('token:' + access_token);
      wx.setStorageSync('token', "");

      wx.login({
        success: function (res) {
          if (res.code) {
            var code = res.code;
            console.log("7777777")
            console.log(res)
            getApp().loginrequest({
              url: api.passport.quick_login,
              method: "post",
              data: {
                code: code
              },
              success: function (res) {
                console.log("quickLoginSuccessful")
                console.log(res)
                wx.hideLoading();
                if (res.code == 200) {
                  const tokenStr = res.data.tokenHead + res.data.token
                  wx.setStorageSync('loginToken', tokenStr)
                  wx.setStorageSync('token', res.data.token);
                  wx.setStorageSync("access_token", res.data.userId);
                  wx.setStorageSync("user_info", {
                    avatar_url: res.data.img,
                    nickname: res.data.username,
                    avatar_url: res.data.icon,
                    // parent: res.data.parent,
                    id: res.data.id
                  });
                  wx.setStorageSync("my_info", {
                    supplyId: res.data.myInfo.supplyId,
                    supplyState: res.data.myInfo.supplyState,
                    myMoney: res.data.myInfo.myMoney,
                    brokerage: res.data.myInfo.brokerage,
                    brokerageTixian: res.data.myInfo.brokerageTixian,

                    moneyTotal: res.data.myInfo.moneyTotal,
                    buyTotal: res.data.myInfo.buyTotal,

                    icon: res.data.myInfo.icon,
                    nickname: res.data.myInfo.nickname,
                    memberLevelId: res.data.myInfo.memberLevelId,
                    id: res.data.myInfo.id,
                    city: res.data.myInfo.city,
                    gender: res.data.myInfo.gender,
                    job: res.data.myInfo.job,
                    phone: res.data.myInfo.phone,
                    birthday: res.data.myInfo.birthday,


                    // parent: res.data.parent,
                  });

                    // if (wx.reLaunch) {
                    //    wx.reLaunch({
                    //   url: '/pages/index/index'
                    //    })
                    //  } else {
                    // this.location('/pages/index/index');
                    //      }
            
                } else {
                  wx.setStorageSync('token', '');
                  wx.setStorageSync("access_token", '');
                }
              }
            });
          }


        }
      });


      // if (access_token) {
      //   if (wx.reLaunch) {
      //     wx.reLaunch({
      //       url: '/pages/index/index'
      //     })
      //   } else {
      //     this.location('/pages/index/index');
      //   }
      // } else {
      //   wx.reLaunch({
      //     url: '/pages/allow/allow'
      //   })
      // }
        //  if (!access_token)
        //  this.login();
    },


    getCatList: function () {
        this.request({
            url: api.default.cat_list,
            data: {
                limit: 15
            },
            success: function (res) {
                if (res.code == 200) {
                    var cat_list = res.data || [];
                    wx.setStorageSync("cat_list", cat_list);
                }
            }
        });
    },


    login: function () {
        var pages = getCurrentPages();
        var page = pages[(pages.length - 1)];

        wx.login({
            success: function (res) {
                if (res.code) {
                    var code = res.code;
                            getApp().request({
                              url: api.passport.quick_login,
                                method: "post",
                                data: {
                                    code: code
                                },
                                success: function (res) {
                                  console.log("quickLoginSuccessful")
                                  console.log(res)
                                    wx.hideLoading();
                                    if (res.code == 200) {
                                        const tokenStr = res.data.tokenHead+res.data.token
                                        wx.setStorageSync('loginToken', tokenStr)
                                        wx.setStorageSync('token', res.data.token);
                                        wx.setStorageSync("access_token", res.data.userId);
                                        wx.setStorageSync("user_info", {
                                            avatar_url: res.data.img,
                                            nickname: res.data.username,
                                            avatar_url: res.data.icon,
                                            // parent: res.data.parent,
                                            id: res.data.id
                                        });
                                      wx.setStorageSync("my_info", {
                                        supplyId: res.data.myInfo.supplyId,
                                        supplyState: res.data.myInfo.supplyState,
                                        myMoney: res.data.myInfo.myMoney,
                                        icon: res.data.myInfo.icon,
                                        nickname: res.data.myInfo.nickname,
                                        // parent: res.data.parent,
                                      });

                                        var parent_id = wx.getStorageSync("parent_id");
                                        var p = getCurrentPages();
                                        // var parent_id = 0;


                                        if (p[0].options.user_id != undefined) {

                                            parent_id = p[0].options.user_id;
                                        }
                                        else if (p[0].options.scene != undefined) {
                                            parent_id = p[0].options.scene;
                                        }
                                        console.log('parentid:' + parent_id, p[0].options.scene, p[0].options.user_id);
                                    

                                        if (page == undefined) {
                                            return;

                                        }
                                        wx.redirectTo({
                                            url: "/" + page.route + "?" + util.objectToUrlParams(page.options),
                                            fail: function () {
                                                wx.switchTab({
                                                    url: "/" + page.route,
                                                });
                                            },
                                        });
                                    } else {
                                      // wx.reLaunch({
                                      //   url: '/pages/allow/allow'
                                      // })
                                        // wx.showToast({
                                        //     title: res.msg
                                        // });
                                    }
                                }
                            });
                        }
                

            }
        });
    },
    request: function (object) {
        var access_token = wx.getStorageSync("access_token");
        console.log('token:' + access_token);
        if (access_token) {
            if (!object.data)
                object.data = {};
            // object.data.access_token = access_token;
        }
        wx.request({
            url: object.url,
            header: object.header || {
                'content-type': 'application/x-www-form-urlencoded',
                'Authorization':wx.getStorageSync('loginToken') // 让每个请求携带自定义token 请根据实际情况自行修改

            },
            data: object.data || {},
            method: object.method || "GET",
            dataType: object.dataType || "json",
            success: function (res) {
                if (res.data.code == -1) {
                    getApp().login();
                } else {
                    if (object.success)
                        object.success(res.data);
                }
            },
            fail: function (res) {
                var app = getApp();
                if (app.is_on_launch) {
                    app.is_on_launch = false;
                    wx.showModal({
                        title: "网络请求出错",
                        content: res.errMsg,
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                if (object.fail)
                                    object.fail(res);
                            }
                        }
                    });
                } else {
                    wx.showToast({
                        title: res.errMsg,
                        image: "/images/icon-warning.png",
                    });
                    if (object.fail)
                        object.fail(res);
                }
            },
            complete: function (res) {
                if (object.complete)
                    object.complete(res);
            }
        });
    },
  loginrequest: function (object) {
    var access_token = wx.getStorageSync("access_token");
    console.log('token:' + access_token);
    if (access_token) {
      if (!object.data)
        object.data = {};
      // object.data.access_token = access_token;
    }
    wx.request({
      url: object.url,
      header: object.header || {
        'content-type': 'application/x-www-form-urlencoded'

      },
      data: object.data || {},
      method: object.method || "GET",
      dataType: object.dataType || "json",
      success: function (res) {
        if (res.data.code == -1) {
          getApp().login();
        } else {
          if (object.success)
            object.success(res.data);
        }
      },
      fail: function (res) {
        var app = getApp();
        if (app.is_on_launch) {
          app.is_on_launch = false;
          wx.showModal({
            title: "网络请求出错",
            content: res.errMsg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                if (object.fail)
                  object.fail(res);
              }
            }
          });
        } else {
          wx.showToast({
            title: res.errMsg,
            image: "/images/icon-warning.png",
          });
          if (object.fail)
            object.fail(res);
        }
      },
      complete: function (res) {
        if (object.complete)
          object.complete(res);
      }
    });
  },
    saveFormId: function (form_id) {
        this.request({
            url: api.user.save_form_id,
            data: {
                form_id: form_id,
            }
        });
    },



});